#include <iostream>
#include <string>
#include <vector>
#include <cstring>
#include <cstdlib>
#include <cstdio>

using namespace std;

string word[10000], s;
int w[10000][26];
vector<int> p[1001];
vector<int> pp[1001];

int trace[1001][2];
int d[1001];
int ntest, n;

void init()
{
	for (int i = 1; i <= s.size(); i++)
	{
		p[i].clear();
		pp[i].clear();
	}

	memset(w, 0, sizeof(w));

	// i is the index of word
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < word[i].size(); j++) w[i][word[i][j]-'a']++;

		int current[26];
		memset(current, 0, sizeof(current));
		for (int j = 0; j < word[i].size()-1; j++) current[s[j]-'a']++;

		int countDif = 0;
		for (int y = 0; y < 26; y++)
			if (current[y] != w[i][y]) countDif++;

		for (int j = word[i].size()-1; j < s.size(); j++)
		{
			int k = j-(word[i].size()-1);

			int pos = s[j]-'a';
			if (current[pos] == w[i][pos]) countDif++;
			current[pos]++;
			if (current[pos] == w[i][pos]) countDif--;

			if ((word[i][0] == s[k]) && (word[i][word[i].size()-1] == s[j]))
				if (countDif == 0)
				{
					p[j+1].push_back(k+1);
					pp[j+1].push_back(i);
				}

			pos = s[k]-'a';
			if (current[pos] == w[i][pos]) countDif++;
			current[pos]--;
			if (current[pos] == w[i][pos]) countDif--;
		}
	}
}

void process()
{
	memset(d, 0, sizeof(d));
	d[0] = 1;
	for (int j = 1; j <= s.size(); j++)
		if (p[j].size() > 0)
			for (int k = 0; k < p[j].size(); k++)
			{
				int i = p[j][k];
				d[j] += d[i-1];
				trace[j][0] = i;
				trace[j][1] = pp[j][k];
			}
}

void out()
{
	if (d[s.size()] > 1) cout << "ambiguous" << endl;
	else
		if (d[s.size()] == 0) cout << "impossible" << endl;
		else
		{
			//cout << "Answer" << endl;
			string result = "";
			int r = s.size();
			while (true)
			{
				int l = trace[r][0];
				int x = trace[r][1];
				if (result == "") result = word[x];
				else result = word[x] + " " + result;
				cout << l << " " << r << endl;
				r = l-1;

				if (r == 67)
				{
					cout << d[67] << endl;
					break;
				}
				if (r <= 0) break;
			}
			cout << result << endl;
		}
}

int main()
{
	freopen("h.in1", "r", stdin);
	freopen("h.out", "w", stdout);

	scanf("%d\n", &ntest);
	while (0 < ntest--)
	{
		getline(cin, s);
		scanf("%d\n", &n);
		for (int i = 0; i < n; i++) getline(cin, word[i]);

		init();
		process();
		out();
	}
	return 0;
}
